package com.xiaoyy.sso.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaoyy.core.common.enums.BoolEnum;
import com.xiaoyy.sso.common.vo.LoginLogVO;
import com.xiaoyy.sso.core.dao.model.SysLogLogin;
import com.xiaoyy.sso.core.dao.model.SysLoginOnline;
import com.xiaoyy.sso.core.integration.LoginLogIntegration;
import com.xiaoyy.sso.core.service.SysLogLoginService;
import com.xiaoyy.sso.core.service.SysLoginOnlineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LoginLogIntegrationImpl implements LoginLogIntegration {
    @Autowired
    SysLogLoginService sysLogLoginService;
    @Autowired
    SysLoginOnlineService sysLoginOnlineService;
    @Override
    @Async("oplogTaskExecutor")
    public void saveLogin(LoginLogVO loginLogVO) {
        Integer ym = Integer.parseInt(DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_PATTERN).substring(0,6));
        loginLogVO.setYm(ym);
        String msg = loginLogVO.getFailReason();
        if (StringUtils.isNotBlank(msg)&&msg.length()>400){
            msg=msg.substring(0,400);
            loginLogVO.setFailReason(msg);
        }
        SysLogLogin sysLogLogin = Convert.convert(SysLogLogin.class,loginLogVO);
        sysLogLogin.setLoginIp(loginLogVO.getReqIp());
        sysLogLoginService.save(sysLogLogin);
        if (BoolEnum.TRUE.getType().equals(sysLogLogin.getLoginFlag())) {
            //登入成功
            SysLoginOnline sysLoginOnline = Convert.convert(SysLoginOnline.class,sysLogLogin);
            sysLoginOnlineService.save(sysLoginOnline);
        }
    }

    @Override
    @Async("oplogTaskExecutor")
    public void saveLogout(String accessToken) {
        if (StringUtils.isBlank(accessToken)){
            return;
        }
        QueryWrapper<SysLogLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysLogLogin::getAccessToken,accessToken);
        SysLogLogin sysLogLogin = sysLogLoginService.getOne(queryWrapper);
        if (sysLogLogin==null){
            return;
        }
        UpdateWrapper<SysLogLogin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysLogLogin::getLogoutTime,new Date())
                .set(SysLogLogin::getOnlineFlag,BoolEnum.FALSE.getType())
                .eq(SysLogLogin::getLoginId,sysLogLogin.getLoginId());
        sysLogLoginService.update(updateWrapper);
        QueryWrapper<SysLoginOnline> delete = new QueryWrapper<>();
        delete.lambda().eq(SysLoginOnline::getAccessToken,accessToken);
        sysLoginOnlineService.remove(delete);
    }
}
